package com.zheng1.envii.ui.screens

import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.Button
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.zheng1.envii.MainViewModel
import com.zheng1.envii.R
import com.zheng1.envii.Screen
import com.zheng1.envii.btutils.BleDeviceStatus
import com.zheng1.envii.btutils.EnvIIBleDeviceData
import com.zheng1.envii.room.entity.EnvIIBleDeviceDataEntity
import kotlinx.coroutines.flow.map


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DeviceControlScreen(
    modifier: Modifier = Modifier,
    navController: NavController,
    deviceAddress: String,
    viewModel: MainViewModel
) {

    val envIIBleDevice = viewModel.findBleDeviceByAddress(deviceAddress)
    if( envIIBleDevice == null ){
        Toast.makeText(navController.context, "设备未连接", Toast.LENGTH_SHORT).show()
        navController.popBackStack(route = Screen.DeviceManagerScreen.route, inclusive = false)
    }

    val connectStatus = envIIBleDevice?.connectStatus?.collectAsState(initial = BleDeviceStatus.DISCONNECTED)

    Scaffold (
        topBar = {
            CenterAlignedTopAppBar(
                colors = TopAppBarDefaults.mediumTopAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primary,
                ),
                title = {
                    Column( verticalArrangement = Arrangement.Center,
                        horizontalAlignment = Alignment.CenterHorizontally) {
                        Text(text = envIIBleDevice?.name?:"N/A")
                        Text(text = envIIBleDevice?.address?:"N/A", fontSize = 15.sp)
                    }
                },
                navigationIcon = {
                    IconButton(onClick = {
                        navController.popBackStack()
                    }) {
                        Icon(imageVector = Icons.Filled.ArrowBack, contentDescription = "null")
                    }
                },
                actions = {
                    if( connectStatus?.value == BleDeviceStatus.CONNECTED ){
                        Text(text = "已连接", fontSize = 15.sp)
                    }else{
                        Text(text = "已断开", fontSize = 15.sp)
                    }
                }
            )
        }
    ) { innerPadding ->
        Column( modifier = Modifier
            .fillMaxWidth()
            .padding(innerPadding)
            .padding(10.dp)
        ) {

            val sensorCurrentData =
                envIIBleDevice?.sensorCurrentData?.collectAsState(
                    initial = EnvIIBleDeviceData(
                        time = "N/A", temperature = "N/A", humidity = "N/A", airpressure = "N/A"
                    )
                )

            Text(text = "当前数据:",modifier = Modifier.padding(10.dp))

            Column(
                Modifier
                    .fillMaxWidth()
                    .padding(10.dp),
                horizontalAlignment = Alignment.Start,
                verticalArrangement = Arrangement.SpaceBetween
            ) {
                val rowModifyPadding = modifier.padding(bottom = 10.dp)
                Row(modifier = rowModifyPadding) {
                    Icon( modifier = Modifier
                        .clip(MaterialTheme.shapes.small)
                        .background(MaterialTheme.colorScheme.primary),
                        painter = painterResource(id = R.drawable.baseline_thermostat_24),
                        contentDescription = "null")
                    if( connectStatus?.value == BleDeviceStatus.CONNECTED ){
                        Text(text = sensorCurrentData?.value?.temperature?:"N/A",
                            modifier = Modifier.padding(start = 5.dp)
                        )
                    }else{
                        Text(text = "N/A",
                            modifier = Modifier.padding(start = 5.dp))
                    }
                    Text(text = "℃")
                }


                Row (modifier = rowModifyPadding){
                    Icon( modifier = Modifier
                        .clip(MaterialTheme.shapes.small)
                        .background(MaterialTheme.colorScheme.primary),
                        painter = painterResource(id = R.drawable.baseline_humidity_24),
                        contentDescription = "null")
                    if( connectStatus?.value == BleDeviceStatus.CONNECTED ){
                        Text(text = sensorCurrentData?.value?.humidity?:"N/A",
                            modifier = Modifier.padding(start = 5.dp))
                    }else{
                        Text(text = "N/A",
                            modifier = Modifier.padding(start = 5.dp))
                    }
                    Text(text = "%")
                }

                Row (modifier = rowModifyPadding){
                    Icon( modifier = Modifier
                        .clip(MaterialTheme.shapes.small)
                        .background(MaterialTheme.colorScheme.primary),
                        painter = painterResource(id = R.drawable.baseline_flight_takeoff_24),
                        contentDescription = "null")
                    if( connectStatus?.value == BleDeviceStatus.CONNECTED ){
                        Text(text = sensorCurrentData?.value?.airpressure?:"N/A",
                            modifier = Modifier.padding(start = 5.dp))
                    }else{
                        Text(text = "N/A",
                            modifier = Modifier.padding(start = 5.dp))
                    }
                    Text(text = "kPa")
                }
            }

            HorizontalDivider(modifier = Modifier.padding(horizontal = 10.dp))

            Row ( modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp, vertical = 10.dp),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically) {
                Text(text = "历史数据:")
                IconButton(
                    modifier = Modifier
                        .padding(end = 10.dp)
                        .clip(RoundedCornerShape(50))
                        .background(MaterialTheme.colorScheme.primary)
                        .size(30.dp),
                    onClick = {
                    envIIBleDevice?.clearHistoryData()
                }) {
                    Icon(imageVector = Icons.Filled.Delete,
                        contentDescription = "null")
                }
            }

            Row (
                modifier = Modifier
                    .fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceAround,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(text = "时间")
                Text(text = "温度(℃)")
                Text(text = "湿度(%)")
                Text(text = "气压(kPa)")
            }

            val sensorHistoryData = envIIBleDevice?.sensorHistoryData?.collectAsState(initial = emptyList())

            sensorHistoryData?.let {
                LazyColumn( modifier = Modifier
                    .fillMaxWidth()
                    .padding(5.dp) ) {
                    items(it.value){ item ->
                        Row ( modifier = Modifier
                            .padding(2.dp)
                            .fillMaxWidth()
                            .height(30.dp)
                            .background(MaterialTheme.colorScheme.background)
                            .clip(MaterialTheme.shapes.medium),
                            horizontalArrangement = Arrangement.SpaceAround,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(text = item.time, modifier = Modifier.padding(start = 10.dp))
                            Text(text = item.temperature, modifier = Modifier.padding(start = 10.dp))
                            Text(text = item.humidity, modifier = Modifier.padding(start = 10.dp))
                            Text(text = item.airpressure, modifier = Modifier.padding(start = 10.dp))
                        }
                    }
                }
            }
        }
    }
}